import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver

#单独运行本文件，获取cookie
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


def getCookie():
    opt = webdriver.ChromeOptions()
    opt.debugger_address = '127.0.0.1:9000'
    driver = webdriver.Chrome(options=opt)
    driver.get('https://work.weixin.qq.com/wework_admin/frame#contacts')
    cookies = driver.get_cookies()
    with open('../datas/datas.yml', 'w+', encoding='utf-8') as f:
        yaml.safe_dump(cookies, f)


class BasePage(object):
    #初始化
    def __init__(self, basedriver : WebDriver=None):
        if basedriver == None:
            self.driver = webdriver.Chrome()
            #先打开网址
            self.driver.get('https://work.weixin.qq.com/')
            #获取文件内的cookie
            with open('../datas/datas.yml', encoding='utf-8') as f:
                cookies = yaml.safe_load(f)
            for cookie in cookies:
                self.driver.add_cookie(cookie)
            #打开首页
            self.driver.get('https://work.weixin.qq.com/wework_admin/frame#index')
        else:
            self.driver = basedriver
    #获取元素
    def find(self, by, locator):
        ele = self.driver.find_element(by, locator)
        return ele
    #获取元素组
    def finds(self, by, locator):
        eles = self.driver.find_elements(by, locator)
        return eles
    #找到元素并点击
    def find_and_click(self, by, locator):
        ele = self.driver.find_element(by, locator)
        ele.click()
    #找到元素并输入
    def find_and_send(self, by, locator, send):
        ele = self.driver.find_element(by, locator)
        ele.send_keys(send)
    def wait_for_click(self, locator, timeout=10):
        WebDriverWait(self.driver, timeout).until(
            expected_conditions.element_to_be_clickable(locator)
        ).click()

if __name__ == '__main__':
    getCookie()